﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BL;
using DB;
using Database;
using Microsoft.Reporting.WinForms;
using System.Collections.ObjectModel;


namespace UI
{
    public partial class MainForm : Form
    {
        int activeRow = 0, activeCol = 0;
        string oldContent;
        Topic topi;
        SubjectItem subject;
        SubjectItem[] list;
        List<Topic> topicList;
        SubjectItemMapper mapper = new SubjectItemMapper();
        DataTable dt;
        bool buttonPressed = false;
       
        
        public MainForm()
        {
            InitializeComponent();
           
            dt = DB.AccessDb.Instance.GetTable("SubjectItem");
            
            subjectsdataGridView.AllowDrop = true;
            subjectsdataGridView.AllowUserToAddRows = true;
            subjectsdataGridView.AllowUserToDeleteRows = true;

            this.subjectsdataGridView.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.subjectsdataGridView_CellValueChanged);
            this.topiksdGVw.UserAddedRow += new System.Windows.Forms.DataGridViewRowEventHandler(this.topiksdGVw_UserAddedRow);
            this.topiksdGVw.UserDeletingRow += new System.Windows.Forms.DataGridViewRowCancelEventHandler(this.topiksdGVw_UserDeletingRow);
            this.topiksdGVw.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.topiksdGVw_CellValueChanged);
            this.subjectsdataGridView.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.subjectsdataGridView_RowsAdded);
            
            this.nagruzkaDGV.UserDeletingRow += new System.Windows.Forms.DataGridViewRowCancelEventHandler(this.dataGridView1_UserDeletingRow);
            this.nagruzkaDGV.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
            int k = 0;
            dataGridTable.Rows.Clear();
            Table table = Table.Instance;
            foreach (TableRow row in table.Rows)
            {
                dataGridTable.Rows.Add(row.Cells);
                dataGridTable.Rows[k].HeaderCell.Style.Alignment =
                    DataGridViewContentAlignment.MiddleCenter;
                string label = ((int)(k / 2 + 1)).ToString();
                if (k % 2 == 0)
                    dataGridTable.Rows[k].HeaderCell.Value = label;
                k++;
            }

            nagruzkaDGV.Enabled = (Subjects.Instance.Items.Length > 0);

            for (int i = 0; i < 6; i++)
                GetColumn(i).DropDownWidth = 300;
            dataGridTable.CellValueChanged += new DataGridViewCellEventHandler(CellValueChange);
            UpdateView();
        }

       
        private void SubjectItemsForm_Load(object sender, EventArgs e)
        {

            this.reportViewer1.RefreshReport();
            reportViewer1.ProcessingMode = ProcessingMode.Local;

            reportViewer1.LocalReport.DataSources.Clear();

            foreach (ReportDataSource source in GetReportDataSources())
            {
                reportViewer1.LocalReport.DataSources.Add(source);
            }

            this.reportViewer1.RefreshReport();
            
            NagruzkaItem[] nagruzkiList = Nagruzki.Instance.Items;
            foreach (NagruzkaItem ni in nagruzkiList)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells.Add(new DataGridViewTextBoxCell());
                
                DataGridViewComboBoxCell cmb1 = new DataGridViewComboBoxCell();
                row.Cells.Add(cmb1);
                cmb1.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                DataGridViewComboBoxCell cmb2 = new DataGridViewComboBoxCell();
                cmb2.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                row.Cells.Add(cmb2);
                row.Cells.Add(new DataGridViewTextBoxCell());

                SubjectItem[] items = Subjects.Instance.Items;
                foreach (SubjectItem si in items)
                {
                    cmb1.Items.Add(si.ToString());
                }

                List<Topic> topicList = Topiki.Instance.SelectSubject(ni.SubjectItem.ID);
                cmb2.Items.Add("");
                for (int i = 0; i < topicList.Count; i++)
                {
                    cmb2.Items.Add(topicList[i].Theme);
                }

                row.Tag = ni.ID;
                row.Cells[0].Value = ni.ID;
                row.Cells[1].Value = ni.Chislo;
                row.Cells[2].Value = ni.SubjectItem.ToString();                
                row.Cells[3].Value = ni.Theme;
                row.Cells[4].Value = ni.Hour;
                nagruzkaDGV.Rows.Add(row);
            }

            list = Subjects.Instance.Items;
            foreach (SubjectItem item in list)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells.Add(new DataGridViewTextBoxCell());
                DataGridViewComboBoxCell cmb = new DataGridViewComboBoxCell();
                cmb.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                cmb.Items.Add(LessonTypes.Лекции.ToString());
                cmb.Items.Add(LessonTypes.Практика.ToString());
                cmb.Items.Add(LessonTypes.Курсовое.ToString());
                cmb.Items.Add(LessonTypes.Дипломное.ToString());
                cmb.Items.Add(LessonTypes.Консультация.ToString());
                cmb.Items.Add(LessonTypes.Экзамен.ToString());
                row.Cells.Add(cmb);
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells[0].Value = item.ID;
                row.Cells[1].Value = item.Faculty;
                row.Cells[2].Value = item.Group;
                row.Cells[3].Value = item.Subject;
                row.Cells[4].Value = item.LessonType.ToString();
                row.Cells[5].Value = item.Hours;
                subjectsdataGridView.Rows.Add(row);
            }
            if (Subjects.Instance.Items.Length > 0)
            {
                subjectsdataGridView.Rows[0].Selected = true;
                long id = long.Parse(subjectsdataGridView.Rows[0].Cells[0].Value.ToString());
                ZapolnitLabel(id);
            }
            if (Nagruzki.Instance.Items.Length > 0)
            {
                nagruzkaDGV.Rows[0].Selected = true;
                SubjectItem si = Subjects.Instance[nagruzkaDGV.Rows[0].Cells[2].Value.ToString()];
                long id = 0;
                for (int i = 0; i < Topiki.Instance.Items.Length; i++)
                {
                    if (Topiki.Instance.Items[i].Subject.ID == si.ID)
                    {
                        id = Topiki.Instance.Items[i].Subject.ID;
                        return;
                    }
                }

                
                ZapolnitHoursLabel(id);
            }



            this.reportViewer1.RefreshReport();
       }
        

        public Collection<ReportDataSource> GetReportDataSources()
        {
            BindingList<JurnalItem> list = new BindingList<JurnalItem>();
            foreach (JurnalItem ji in Jurnaly.Instance.Items)
            {
                list.Add(ji);
            }

            Collection<ReportDataSource> sources = new Collection<ReportDataSource>();

            ReportDataSource dataSource = new ReportDataSource();
            dataSource.Value = list;
            dataSource.Name = "BL_JurnalItem";
            sources.Add(dataSource);

            return sources;
        }
        

        private void copyBtn_Click_1(object sender, EventArgs e)
        {
            if (subjectsdataGridView.SelectedRows.Count == 0 || 
                subjectsdataGridView.SelectedRows[0].Index == subjectsdataGridView.Rows.Count - 1)
                return;
            int pos = subjectsdataGridView.SelectedRows[0].Index;
            try
            {
                subject = new SubjectItem();
                subject.ID = Subjects.Instance.FreeID;
                subject.Faculty = subjectsdataGridView.Rows[pos].Cells[1].Value.ToString();
                subject.Group = subjectsdataGridView.Rows[pos].Cells[2].Value.ToString();
                subject.Subject = subjectsdataGridView.Rows[pos].Cells[3].Value.ToString();

                subject.LessonType = LessonTypeConverter.Convert(subjectsdataGridView.Rows[pos].Cells[4].Value.ToString());
                subject.Hours = Convert.ToInt32(subjectsdataGridView.Rows[pos].Cells[5].Value);
                topicList = new List<Topic>();

                for (int i = 0; i < topiksdGVw.RowCount - 1; i++)
                {
                    topi = new Topic();
                    topi.ID = Topiki.Instance.FreeID;
                    topi.Subject = subject;
                    topi.Theme = topiksdGVw.Rows[i].Cells[1].Value.ToString();
                    topi.Hours = int.Parse(topiksdGVw.Rows[i].Cells[2].Value.ToString());
                    topicList.Add(topi);
                }
            }
            catch
            {
                
            }
        }

        private void pasteBtn_Click_1(object sender, EventArgs e)
        {
            buttonPressed = true;
            try
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells.Add(new DataGridViewTextBoxCell());
                DataGridViewComboBoxCell cmb = new DataGridViewComboBoxCell();
                cmb.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                cmb.Items.Add(LessonTypes.Лекции.ToString());
                cmb.Items.Add(LessonTypes.Практика.ToString());
                cmb.Items.Add(LessonTypes.Курсовое.ToString());
                cmb.Items.Add(LessonTypes.Дипломное.ToString());
                cmb.Items.Add(LessonTypes.Консультация.ToString());
                cmb.Items.Add(LessonTypes.Экзамен.ToString());
                row.Cells.Add(cmb);
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells[0].Value = Subjects.Instance.FreeID;
                subject.ID = long.Parse(row.Cells[0].Value.ToString());
                row.Cells[1].Value = subject.Faculty;
                row.Cells[2].Value = subject.Group;
                row.Cells[3].Value = subject.Subject;
                row.Cells[4].Value = subject.LessonType.ToString();
                row.Cells[5].Value = subject.Hours;
                
                
                subjectsdataGridView.Rows.Add(row);
                topiksdGVw.Rows.Clear();
                for (int i = 0; i < topicList.Count; i++)
                {
                    DataGridViewRow r = new DataGridViewRow();
                    r.Cells.Add(new DataGridViewTextBoxCell());
                    r.Cells.Add(new DataGridViewTextBoxCell());
                    r.Cells.Add(new DataGridViewTextBoxCell());
                    r.Cells[0].Value = Topiki.Instance.FreeID;
                    topicList[i].ID=Topiki.Instance.FreeID;
                    r.Cells[1].Value = topicList[i].Theme;
                    r.Cells[2].Value = topicList[i].Hours;
                    topiksdGVw.Rows.Add(r);                    
                }
                buttonPressed = false;
                
            }
            catch
            {
                
            }
        }

        

        
        private void subjectsdataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            if (Column3.Items.Count == 0)
            {
                Column3.Items.Add(LessonTypes.Лекции.ToString());
                Column3.Items.Add(LessonTypes.Практика.ToString());
                Column3.Items.Add(LessonTypes.Курсовое.ToString());
                Column3.Items.Add(LessonTypes.Дипломное.ToString());
                Column3.Items.Add(LessonTypes.Консультация.ToString());
                Column3.Items.Add(LessonTypes.Экзамен.ToString());
            }
            SubjectItem si = new SubjectItem();
            si.ID = Subjects.Instance.FreeID;
            subjectsdataGridView.Rows[e.Row.Index-1].Cells[0].Value = si.ID;

            Subjects.Instance.Add(si);
            SubjectItemMapper tMapper = new SubjectItemMapper();
            tMapper.Insert(si);
            
            
            UpdateView();
            AccessDb.Instance.Commit();
            nagruzkaDGV.Enabled = (Subjects.Instance.Items.Length > 0);

            reportViewer1.LocalReport.DataSources.Clear();

            foreach (ReportDataSource source in GetReportDataSources())
            {
                reportViewer1.LocalReport.DataSources.Add(source);
            }

            this.reportViewer1.RefreshReport();
        }

        private void subjectsdataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (subjectsdataGridView.Rows[e.RowIndex].Cells[0].Value != null)
            {
                Int64 id = Int64.Parse(subjectsdataGridView.Rows[e.RowIndex].Cells[0].Value.ToString());
                SubjectItem si = new SubjectItem();
                si.ID = id;

                if (subjectsdataGridView.Rows[e.RowIndex].Cells[1].Value != null)
                    si.Faculty = subjectsdataGridView.Rows[e.RowIndex].Cells[1].Value.ToString();
                if (subjectsdataGridView.Rows[e.RowIndex].Cells[2].Value != null)
                {
                    si.Group = subjectsdataGridView.Rows[e.RowIndex].Cells[2].Value.ToString();
                    foreach (Topic t in Topiki.Instance.Items)
                    {
                        if (t.Subject.ID == id)
                        {
                            t.Subject.Group = si.Group;
                            TopicMapper tMapper = new TopicMapper();
                            tMapper.UpdateEntity(t);
                            AccessDb.Instance.Commit();
                        }
                    }
                    foreach (NagruzkaItem ni in Nagruzki.Instance.Items)
                    {
                        if (ni.SubjectItem.ID == id)
                        {
                            ni.SubjectItem.Group = si.Group;                            
                            NagruzkaMapper nMapper = new NagruzkaMapper();
                            nMapper.UpdateEntity(ni);
                            AccessDb.Instance.Commit();
                        }
                    }
                    
                }
                if (subjectsdataGridView.Rows[e.RowIndex].Cells[3].Value != null)
                {
                    si.Subject = subjectsdataGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
                    foreach (Topic t in Topiki.Instance.Items)
                    {
                        if (t.Subject.ID == id)
                        {
                            t.Subject.Subject = si.Subject;
                            TopicMapper tMapper = new TopicMapper();
                            tMapper.UpdateEntity(t);
                            AccessDb.Instance.Commit();
                        }
                    }
                    foreach (NagruzkaItem ni in Nagruzki.Instance.Items)
                    {
                        if (ni.SubjectItem.ID == id)
                        {
                            ni.SubjectItem.Subject = si.Subject;
                           
                            NagruzkaMapper nMapper = new NagruzkaMapper();
                            nMapper.UpdateEntity(ni);
                            AccessDb.Instance.Commit();
                        }
                    }
                    
                }
                if (subjectsdataGridView.Rows[e.RowIndex].Cells[4].Value != null)
                {
                    si.LessonType = LessonTypeConverter.Convert(subjectsdataGridView.Rows[e.RowIndex].Cells[4].Value.ToString());
                    foreach (Topic t in Topiki.Instance.Items)
                    {
                        if (t.Subject.ID == id)
                        {
                            t.Subject.LessonType = si.LessonType;
                            TopicMapper tMapper = new TopicMapper();
                            tMapper.UpdateEntity(t);
                            AccessDb.Instance.Commit();
                        }
                    }
                    foreach (NagruzkaItem ni in Nagruzki.Instance.Items)
                    {
                        if (ni.SubjectItem.ID == id)
                        {
                            ni.SubjectItem.LessonType = si.LessonType;
                            NagruzkaMapper nMapper = new NagruzkaMapper();
                            nMapper.UpdateEntity(ni);
                            AccessDb.Instance.Commit();                            
                        }
                    }
                    
                }
                try
                {
                    if (subjectsdataGridView.Rows[e.RowIndex].Cells[5].Value != null)
                        si.Hours = int.Parse(subjectsdataGridView.Rows[e.RowIndex].Cells[5].Value.ToString());
                }
                catch
                {
                    subjectsdataGridView.Rows[e.RowIndex].Cells[5].Value = si.Hours = 2;
                }
                Subjects.Instance[id] = si;
                SubjectItemMapper sMapper = new SubjectItemMapper();
                sMapper.UpdateEntity(si);
                AccessDb.Instance.Commit();
                UpdateView();
                reportViewer1.LocalReport.DataSources.Clear();

                foreach (ReportDataSource source in GetReportDataSources())
                {
                    reportViewer1.LocalReport.DataSources.Add(source);
                }

                this.reportViewer1.RefreshReport();

                this.nagruzkaDGV.CellValueChanged -= new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
                for (int j = 0; j < nagruzkaDGV.Rows.Count - 1; j++)
                {
                    DataGridViewComboBoxCell cmb1 = (DataGridViewComboBoxCell)nagruzkaDGV.Rows[j].Cells[2];
                    cmb1.Items.Clear();
                    foreach (SubjectItem subItem in Subjects.Instance.Items)
                        cmb1.Items.Add(subItem.ToString());
                    NagruzkaItem nagI = Nagruzki.Instance[long.Parse(nagruzkaDGV.Rows[j].Cells[0].Value.ToString())];
                    nagruzkaDGV.Rows[j].Cells[2].Value = nagI.SubjectItem.ToString();
                }
                this.nagruzkaDGV.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
               
            }
            else
                return;
        }

        private void subjectsdataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            DialogResult res = MessageBox.Show("Вы действительно хотите удалить этот предмет?", "Подтверждение удаления", MessageBoxButtons.YesNo);
            if (res == DialogResult.No)
            {
                e.Cancel = true;
                return;
            }

            if (e.Row.Cells[0].Value == null)
            {
                e.Cancel = true;
                return;
            }
            SubjectItem si = Subjects.Instance[long.Parse(e.Row.Cells[0].Value.ToString())];
            List<Topic> top = Topiki.Instance.SelectSubject(si.ID);
            {
                foreach (NagruzkaItem item in Nagruzki.Instance.Items)
                {
                    if (item.SubjectItem.ID == si.ID)
                        DeleteNagruzka(item, true);
                }
            }
           
            if (subjectsdataGridView.Rows.Count < 3)
                SpisokTem.Text = "Ничего не выбрано";
            else
            {
                long subjID = long.Parse(subjectsdataGridView.Rows[e.Row.Index].Cells[0].Value.ToString());
                List<Topic> topiki = Topiki.Instance.SelectSubject(subjID);
                int sum = 0;
                foreach (Topic t in topiki)
                    sum += t.Hours;

                string str = "Список тем (заполнено ";
                str += sum.ToString() + " / ";
                str += "осталось " + ((int)(Subjects.Instance[subjID].Hours - sum)).ToString() + ")";
                SpisokTem.Text = str;
            }

            SubjectItemMapper tMapper = new SubjectItemMapper();
            Subjects.Instance.Delete(si.ID);
            tMapper.DeleteEntity(si);

            UpdateView();
            AccessDb.Instance.Commit();
            nagruzkaDGV.Enabled = (Subjects.Instance.Items.Length > 0);

            reportViewer1.LocalReport.DataSources.Clear();

            foreach (ReportDataSource source in GetReportDataSources())
            {
                reportViewer1.LocalReport.DataSources.Add(source);
            }

            this.reportViewer1.RefreshReport();
           
        }

        private void subjectsdataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            list = Subjects.Instance.Items;
            if ((e.RowIndex > (list.Length-1)) && (e.RowIndex!=subjectsdataGridView.Rows.Count-1) && buttonPressed)
            {
                SubjectItem si = new SubjectItem();
                si.ID = Subjects.Instance.FreeID;
                si.Faculty = subjectsdataGridView.Rows[e.RowIndex].Cells[1].Value.ToString();
                si.Group = subjectsdataGridView.Rows[e.RowIndex].Cells[2].Value.ToString();
                si.Subject = subjectsdataGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
                si.LessonType = LessonTypeConverter.Convert(subjectsdataGridView.Rows[e.RowIndex].Cells[4].Value.ToString());
                si.Hours = int.Parse(subjectsdataGridView.Rows[e.RowIndex].Cells[5].Value.ToString());
                subjectsdataGridView.Rows[e.RowIndex].Cells[0].Value = si.ID;
                
                Subjects.Instance.Add(si);
                SubjectItemMapper tMapper = new SubjectItemMapper();

                subjectsdataGridView.Rows[e.RowIndex].Cells[0].Value = si.ID.ToString(); ;
                tMapper.Insert(si);
                AccessDb.Instance.Commit();
                UpdateView();
                buttonPressed = true;
            }
            nagruzkaDGV.Enabled = (Subjects.Instance.Items.Length > 0);

            reportViewer1.LocalReport.DataSources.Clear();

            foreach (ReportDataSource source in GetReportDataSources())
            {
                reportViewer1.LocalReport.DataSources.Add(source);
            }

            this.reportViewer1.RefreshReport();
        }

        private void subjectsdataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            topiksdGVw.Enabled = true;
            topiksdGVw.Visible = true;
            topiksdGVw.Rows.Clear();
            SelectRow(e.RowIndex);
        }

        void SelectRow(int rowIndex)
        {
            if (rowIndex == subjectsdataGridView.Rows.Count - 1)
            {
                SpisokTem.Text = "Не выбран предмет";
                topiksdGVw.Enabled = false;
                return;
            }
            if (! buttonPressed)
            {
                long id = long.Parse(subjectsdataGridView.Rows[rowIndex].Cells[0].Value.ToString());
                List<Topic> list = Topiki.Instance.SelectSubject(id);
                foreach (Topic t in list)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    row.Cells.Add(new DataGridViewTextBoxCell());
                    row.Cells.Add(new DataGridViewTextBoxCell());
                    row.Cells.Add(new DataGridViewTextBoxCell());
                    row.Cells[0].Value = t.ID;
                    row.Cells[1].Value = t.Theme;
                    row.Cells[2].Value = t.Hours;
                    topiksdGVw.Rows.Add(row);
                }

                

                ZapolnitLabel(id);
            }
        }

        void ZapolnitLabel(long id)
        {
            string str = "Список тем (заполнено ";
            int th = TotalHours(id);
            str += th.ToString() + " / ";
            str += "осталось " + ((int)(Subjects.Instance[id].Hours - th)).ToString() + ")";
            SpisokTem.Text = str;
        }

        int TotalHours(long id)
        {
            int totalHours = 0;
            List<Topic> list = Topiki.Instance.SelectSubject(id);
            for (int i = 0; i < list.Count; i++)
            {
                totalHours += list[i].Hours;
            }              
            
               
            return totalHours;
        }

        private void topiksdGVw_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            Topic t = new Topic();
            t.ID = Topiki.Instance.FreeID;
            long id = long.Parse(subjectsdataGridView.SelectedRows[0].Cells[0].Value.ToString());
            t.Subject = Subjects.Instance[id];
            Topiki.Instance.Add(t);
            TopicMapper tMapper = new TopicMapper();
            tMapper.Insert(t);

            topiksdGVw.Rows[e.Row.Index - 1].Cells[0].Value = t.ID.ToString();
            AccessDb.Instance.Commit();
            subjectsdataGridView.Invalidate();
            topiksdGVw.Rows[e.Row.Index - 1].Cells[2].Value = 2;
        }

        private void topiksdGVw_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            Topic t = Topiki.Instance[long.Parse(e.Row.Cells[0].Value.ToString())];

            foreach (NagruzkaItem ni in Nagruzki.Instance.Items)
            {
                if (ni.Theme == t.Theme && t.Subject.ID == ni.SubjectItem.ID)
                    DeleteNagruzka(ni, true);
            }

            TopicMapper tMapper = new TopicMapper();
            tMapper.DeleteEntity(t);

            Topiki.Instance.Delete(t.ID);
            AccessDb.Instance.Commit();
            ZapolnitLabel(t.Subject.ID);
            subjectsdataGridView.Invalidate();
        }

        private void topiksdGVw_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            Int64 id = Int64.Parse(topiksdGVw.Rows[e.RowIndex].Cells[0].Value.ToString());
            Topic t = new Topic();
            t.ID = id;
            long ID = long.Parse(subjectsdataGridView.SelectedRows[0].Cells[0].Value.ToString());
            t.Subject = Subjects.Instance[ID];
            if (topiksdGVw.Rows[e.RowIndex].Cells[1].Value != null)
            {
                t.Theme = topiksdGVw.Rows[e.RowIndex].Cells[1].Value.ToString();                
            }
            Topiki.Instance[id] = t;
            TopicMapper tMapper = new TopicMapper();
            if (topiksdGVw.Rows[e.RowIndex].Cells[2].Value != null)
            {
                int oldHours = t.Hours;
                try
                {
                    t.Hours = int.Parse(topiksdGVw.Rows[e.RowIndex].Cells[2].Value.ToString());
                }
                catch
                {
                    topiksdGVw.Rows[e.RowIndex].Cells[2].Value = t.Hours = 1;
                }
                if (Subjects.Instance[t.Subject.ID].Hours >= TotalHours(t.Subject.ID))
                {
                    ZapolnitLabel(ID);
                }
                else
                {
                    topiksdGVw.Rows[e.RowIndex].Cells[2].Value = t.Hours = oldHours;
                    MessageBox.Show("Общее число часов больше допустимого!!!");
                    return;
                }
            }
            tMapper.UpdateEntity(t);
            AccessDb.Instance.Commit();
            subjectsdataGridView.Invalidate();
        }

        private void dataGridTable_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex % 2 == 0)
                return;
            int y = e.RowBounds.Bottom - 1;
            int left = dataGridTable.RowHeadersWidth;
            int right = left + dataGridTable.Columns.GetColumnsWidth(DataGridViewElementStates.Visible);
            Pen pen = new Pen(Color.Black, 2);
            e.Graphics.DrawLine(pen, 0, y, right, y);
        }

        private void dataGridTable_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.ForeColor = (e.RowIndex % 2 == 0) ? Color.Red : Color.Blue;
        }

        private void dataGridTable_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == -1 || e.RowIndex == -1)
                return;
            activeRow = e.RowIndex;
            activeCol = e.ColumnIndex;
            oldContent = "";
            object cell = dataGridTable.Rows[activeRow].Cells[activeCol].Value;
            if (cell != null)
                oldContent = cell.ToString();
        }

        private void CellValueChange(object sender, DataGridViewCellEventArgs e)
        {
            dataGridTable.CellValueChanged -= new DataGridViewCellEventHandler(CellValueChange);
            List<TableItem> tItems = Table.Instance.GetItemsAtDay((Days)(e.ColumnIndex), (Weeks)(e.RowIndex % 2));
            if (tItems.Count >= 3)
            {
                dataGridTable.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                MessageBox.Show("Не больше 3-х пар в день!");
                dataGridTable.CellValueChanged += new DataGridViewCellEventHandler(CellValueChange);
                return;
            }
            Table table = Table.Instance;
            string value = "";
            object cell = dataGridTable.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            if (cell != null)
                value = cell.ToString();
            TableItem ti = table.ChangeCell(e.RowIndex, e.ColumnIndex, value);
            TableItemMapper tiMapper = new TableItemMapper();
            if (value != oldContent)
            {
                if (value == "")
                {
                    tiMapper.DeleteEntity(ti);
                    AccessDb.Instance.Commit();
                }
                else
                {
                    if (oldContent == "")
                    {
                        tiMapper.Insert(ti);
                        AccessDb.Instance.Commit();
                    }
                    else
                    {
                        tiMapper.UpdateEntity(ti);
                        AccessDb.Instance.Commit();
                    }
                }
            }
            dataGridTable.CellValueChanged += new DataGridViewCellEventHandler(CellValueChange);
        }

        private DataGridViewComboBoxColumn GetColumn(int index)
        {
            switch (index)
            {
                case 0: return Monday;
                case 1: return Tuesday;
                case 2: return Wednesday;
                case 3: return Thursday;
                case 4: return Friday;
                case 5: return Saturday;
            }
            return null;
        }

        private void UpdateView()
        {
            dataGridTable.CellValueChanged -= new DataGridViewCellEventHandler(CellValueChange);

            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 16; j++)
                {
                    dataGridTable.Rows[j].Cells[i].Value = "";
                }
            }

            for (int i = 0; i < 6; i++)
            {
                GetColumn(i).Items.Clear();
                GetColumn(i).Items.Add("");
            }
            Subjects subj = Subjects.Instance;
            foreach (SubjectItem si in subj.Items)
            {
                for (int j = 0; j < 6; j++)
                {
                    if (si.LessonType == LessonTypes.Лекции || si.LessonType == LessonTypes.Практика)
                        GetColumn(j).Items.Add(si.ToString());
                }
            }

            TableRow[] rows = Table.Instance.Rows;
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 16; j++)
                {
                    string str = (string)rows[j].Cells[i];
                    if (str != "")
                    {
                        if (Subjects.Instance[str].LessonType == LessonTypes.Дипломное ||
                            Subjects.Instance[str].LessonType == LessonTypes.Курсовое ||
                            Subjects.Instance[str].LessonType == LessonTypes.Консультация ||
                            Subjects.Instance[str].LessonType == LessonTypes.Экзамен)
                        {
                            TableItem ti = Table.Instance.ChangeCell(j, i, "");
                            TableItemMapper tiMapper = new TableItemMapper();
                            tiMapper.DeleteEntity(ti);
                            continue;
                        }
                    }
                    dataGridTable.Rows[j].Cells[i].Value = str;
                }
            }
            dataGridTable.CellValueChanged += new DataGridViewCellEventHandler(CellValueChange);
        }

        private void subjectsdataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            int index = e.RowIndex;
            if ((index == subjectsdataGridView.Rows.Count - 1) || (subjectsdataGridView.Rows[index].Cells[5].Value == null))
                return;
            int hours = 0;
            List<Topic> topiki = Topiki.Instance.SelectSubject(long.Parse(subjectsdataGridView.Rows[index].Cells[0].Value.ToString()));
            for (int i = 0; i < topiki.Count; i++)
            {
                hours += topiki[i].Hours;
            }
            bool loaded = hours < int.Parse(subjectsdataGridView.Rows[index].Cells[5].Value.ToString());
            e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor = (loaded) ? Color.Red : Color.Black;
        }

        

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {          
            
            this.nagruzkaDGV.CellValueChanged -= new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
            NagruzkaItem ni = null;
            if (nagruzkaDGV.Rows[e.RowIndex].Cells[0].Value == null)
            {
                ni = AddRowToNagruzka(nagruzkaDGV.Rows[e.RowIndex]);
            }
            else
            {
                ni = Nagruzki.Instance[(long)nagruzkaDGV.Rows[e.RowIndex].Tag];
            }


            DataGridViewComboBoxCell cmb1 = (DataGridViewComboBoxCell)nagruzkaDGV.Rows[e.RowIndex].Cells[3];
            SubjectItem sub = Subjects.Instance[nagruzkaDGV.Rows[e.RowIndex].Cells[2].Value.ToString()];
            List<Topic> top = Topiki.Instance.SelectSubject(sub.ID);
            if (ni.SubjectItem.ToString() != nagruzkaDGV.Rows[e.RowIndex].Cells[2].Value.ToString())
            {
                cmb1.Items.Clear();
                foreach (Topic t in top)
                    cmb1.Items.Add(t.Theme);
                nagruzkaDGV.Rows[e.RowIndex].Cells[3].Value = cmb1.Items[0];
            }

            if (nagruzkaDGV.Rows[e.RowIndex].Cells[2].Value != null)
                ni.SubjectItem = Subjects.Instance[nagruzkaDGV.Rows[e.RowIndex].Cells[2].Value.ToString()];

            if (nagruzkaDGV.Rows[e.RowIndex].Cells[3].Value != null)
                ni.Theme = nagruzkaDGV.Rows[e.RowIndex].Cells[3].Value.ToString();



            if (nagruzkaDGV.Rows[e.RowIndex].Cells[4].Value != null)            
                ni.Hour = int.Parse(nagruzkaDGV.Rows[e.RowIndex].Cells[4].Value.ToString());
            if (nagruzkaDGV.Rows[e.RowIndex].Cells[1].Value != null)
                ni.Chislo = nagruzkaDGV.Rows[e.RowIndex].Cells[1].Value.ToString();
            Nagruzki.Instance[ni.ID] = ni;
            NagruzkaMapper nMapper = new NagruzkaMapper();
            nMapper.UpdateEntity(ni);
            AccessDb.Instance.Commit();

            JurnalItem item = new JurnalItem();
            item.Id = ni.ID.ToString();
            item.SubjectItem = ni.SubjectItem.Subject;
            item.Chislo = ni.Chislo;
            item.Group = ni.SubjectItem.Group;
            item.Theme = ni.Theme;
            item.Faculty = ni.SubjectItem.Faculty;
            if (ni.SubjectItem.LessonType == LessonTypes.Дипломное || ni.SubjectItem.LessonType == LessonTypes.Курсовое || ni.SubjectItem.LessonType == LessonTypes.Консультация || ni.SubjectItem.LessonType == LessonTypes.Экзамен)
                item.Prochee = ni.Hour.ToString();
            if (ni.SubjectItem.LessonType == LessonTypes.Лекции)
                item.Lecture = ni.Hour.ToString();
            if (ni.SubjectItem.LessonType == LessonTypes.Практика)
                item.Practika = ni.Hour.ToString();
            Jurnaly.Instance[item.Id] = item;

            reportViewer1.LocalReport.DataSources.Clear();

            foreach (ReportDataSource source in GetReportDataSources())
            {
                reportViewer1.LocalReport.DataSources.Add(source);
            }

            this.reportViewer1.RefreshReport();

            this.nagruzkaDGV.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
            SubjectItem si = Subjects.Instance[nagruzkaDGV.Rows[e.RowIndex].Cells[2].Value.ToString()];
            
            
        }

        // возврат null, если нет предметов
        private NagruzkaItem AddRowToNagruzka(DataGridViewRow row)
        {
            NagruzkaItem ni = new NagruzkaItem();
            ni.ID = Nagruzki.Instance.FreeID;
            ni.SubjectItem = Subjects.Instance.Items[0];
            ni.Theme = Topiki.Instance.SelectSubject(ni.SubjectItem.ID)[0].Theme;
            Nagruzki.Instance.Add(ni);
            row.Cells[0].Value = ni.ID;
            row.Tag = ni.ID;

            DataGridViewComboBoxCell cmb1 = (DataGridViewComboBoxCell)row.Cells[2];
            foreach (SubjectItem si2 in Subjects.Instance.Items)
            {
                if (Topiki.Instance.SelectSubject(si2.ID).Count > 0)
                    cmb1.Items.Add(si2.ToString());
            }
            row.Cells[2].Value = ni.SubjectItem.ToString();

            DataGridViewComboBoxCell cmb2 = (DataGridViewComboBoxCell)row.Cells[3];
            foreach (Topic t in Topiki.Instance.SelectSubject(ni.SubjectItem.ID))
                cmb2.Items.Add(t.Theme);
            row.Cells[3].Value = cmb2.Items[0];

            row.Cells[4].Value = 2;
            NagruzkaMapper nMapper = new NagruzkaMapper();
            nMapper.Insert(ni);
            AccessDb.Instance.Commit();

            JurnalItem item = new JurnalItem();
            item.Id = ni.ID.ToString();
            item.Chislo = ni.Chislo;
            item.SubjectItem = ni.SubjectItem.Subject;
            item.Group = ni.SubjectItem.Group;
            item.Theme = ni.Theme;
            item.Faculty = ni.SubjectItem.Faculty;
            if (ni.SubjectItem.LessonType == LessonTypes.Дипломное || ni.SubjectItem.LessonType == LessonTypes.Курсовое || ni.SubjectItem.LessonType == LessonTypes.Консультация || ni.SubjectItem.LessonType == LessonTypes.Экзамен)
                item.Prochee = ni.Hour.ToString();
            if (ni.SubjectItem.LessonType == LessonTypes.Лекции)
                item.Lecture = ni.Hour.ToString();
            if (ni.SubjectItem.LessonType == LessonTypes.Практика)
                item.Practika = ni.Hour.ToString();
            Jurnaly.Instance.Add(item);
            return ni;
        }
        

        private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            NagruzkaItem ni = Nagruzki.Instance[(long)e.Row.Tag];
            DeleteNagruzka(ni, false);

            reportViewer1.LocalReport.DataSources.Clear();

            foreach (ReportDataSource source in GetReportDataSources())
            {
                reportViewer1.LocalReport.DataSources.Add(source);
            }

            this.reportViewer1.RefreshReport();
        }

        private void DeleteNagruzka(NagruzkaItem ni, bool deleteFromTable)
        {
            DataGridViewRow r = null;
            foreach (DataGridViewRow row in nagruzkaDGV.Rows)
            {
                if ((long)row.Tag == ni.ID)
                {
                    r = row;
                    break;
                }
            }
            if (deleteFromTable)
                nagruzkaDGV.Rows.Remove(r);
            NagruzkaMapper nMapper = new NagruzkaMapper();
            nMapper.DeleteEntity(ni);
            AccessDb.Instance.Commit();
            Jurnaly.Instance.Delete(ni.ID.ToString());

            Nagruzki.Instance.Delete(ni.ID);
        }

        void ZapolnitHoursLabel(long id)
        {
            string str = "Список тем (заполнено ";
            int th = TotalThemeHours(id);
            str += th.ToString() + " / ";
            str += "осталось " + ((int)(Topiki.Instance[id].Hours - th)).ToString() + ")";
            hoursLabel.Text = str;
        }

        private int TotalThemeHours(long id)
        {
            int totalHours = 0;
            try
            {
                
                Topic t = Topiki.Instance[id];
                if (t != null)
                {
                    for (int i = 0; i < nagruzkaDGV.Rows.Count - 1; i++)
                    {
                        if ((t.Theme == nagruzkaDGV.Rows[i].Cells[3].Value.ToString()) && (t.Subject.ToString() == nagruzkaDGV.Rows[i].Cells[2].Value.ToString()))
                            totalHours += int.Parse(nagruzkaDGV.Rows[i].Cells[4].Value.ToString());
                    }
                }
                
            }
            catch { }
            return totalHours;
        }

        private void nagruzkaDGV_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == nagruzkaDGV.Rows.Count - 1)
            {
                hoursLabel.Text = "Не выбран предмет";
                
                return;
            }

            SubjectItem si = Subjects.Instance[nagruzkaDGV.Rows[e.RowIndex].Cells[2].Value.ToString()];
            foreach (Topic t in Topiki.Instance.SelectSubject(si.ID))
            {
                if (t.Theme == nagruzkaDGV.Rows[e.RowIndex].Cells[3].Value.ToString())
                {
                    ZapolnitHoursLabel(t.ID);
                    return;
                }
            }         
           
            
        }

        private void topiksdGVw_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            
            if ( (e.RowIndex != topiksdGVw.Rows.Count -1) && buttonPressed)
            {
                
                Topic t = new Topic();
                t.ID = Topiki.Instance.FreeID;
                t.Theme = topiksdGVw.Rows[e.RowIndex].Cells[1].Value.ToString();
                t.Hours = int.Parse(topiksdGVw.Rows[e.RowIndex].Cells[2].Value.ToString());
                long id = long.Parse(subjectsdataGridView.Rows[subjectsdataGridView.Rows.Count-2].Cells[0].Value.ToString());
                t.Subject = Subjects.Instance[id];        
                topiksdGVw.Rows[e.RowIndex].Cells[0].Value = t.ID;

                Topiki.Instance.Add(t);
                TopicMapper tMapper = new TopicMapper();
                
                tMapper.Insert(t);
                AccessDb.Instance.Commit();
                UpdateView();
                
            }
        }
        

        private void nagruzkaDGV_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
        }

        private void nagruzkaDGV_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            InputBox box = new InputBox();
            DialogResult res = box.ShowDialog();
            if (res == DialogResult.Cancel)
                return;
            
            NagruzkaMapper nMapper = new NagruzkaMapper();
            nMapper.ClearAll();
            DateTime start = box.startDate.Value;
            DateTime end = box.endDate.Value;            
            List<NagruzkaItem> nagruzki = Nagruzki.Instance.Generate(start,end);

            foreach (DataGridViewRow dr in nagruzkaDGV.Rows)
            {
                for (int i = 0; i < Jurnaly.Instance.Items.Length; i++)
                    if (dr.Tag.ToString() == Jurnaly.Instance.Items[i].Id)
                        Jurnaly.Instance.Delete(dr.Tag.ToString());
            }
            nagruzkaDGV.Rows.Clear();
            for (int i = 0; i < nagruzki.Count; i++)
            {
                DataGridViewRow dr = new DataGridViewRow();
                dr.Cells.Add(new DataGridViewTextBoxCell());
                dr.Tag = dr.Cells[0].Value = nagruzki[i].ID;
                dr.Cells.Add(new DataGridViewTextBoxCell());
                dr.Cells[1].Value = nagruzki[i].Chislo;
                DataGridViewComboBoxCell cmb = new DataGridViewComboBoxCell();
                cmb.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                for (int j = 0; j < Subjects.Instance.Items.Length; j++)
                {
                    cmb.Items.Add(Subjects.Instance.Items[j].ToString());
                }
                dr.Cells.Add(cmb);
                dr.Cells[2].Value = nagruzki[i].SubjectItem.ToString();

                DataGridViewComboBoxCell cmb2 = new DataGridViewComboBoxCell();
                cmb2.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                List<Topic>top = Topiki.Instance.SelectSubject(nagruzki[i].SubjectItem.ID);
                for (int j = 0; j < top.Count; j++)
                {
                    cmb2.Items.Add(top[j].Theme);
                }
                dr.Cells.Add(cmb2);
                dr.Cells[3].Value = nagruzki[i].Theme;
                dr.Cells.Add(new DataGridViewTextBoxCell());
                dr.Cells[4].Value = nagruzki[i].Hour;
                nagruzkaDGV.Rows.Add(dr);
                nMapper.Insert(nagruzki[i]);

                JurnalItem item = new JurnalItem();
                item.Id = nagruzki[i].ID.ToString();
                item.SubjectItem = nagruzki[i].SubjectItem.Subject;
                item.Chislo = nagruzki[i].Chislo;
                item.Group = nagruzki[i].SubjectItem.Group;
                item.Theme = nagruzki[i].Theme;
                item.Faculty = nagruzki[i].SubjectItem.Faculty;
                if (nagruzki[i].SubjectItem.LessonType == LessonTypes.Дипломное || nagruzki[i].SubjectItem.LessonType == LessonTypes.Курсовое || nagruzki[i].SubjectItem.LessonType == LessonTypes.Экзамен || nagruzki[i].SubjectItem.LessonType == LessonTypes.Консультация)
                    item.Prochee = nagruzki[i].Hour.ToString();
                if (nagruzki[i].SubjectItem.LessonType == LessonTypes.Лекции)
                    item.Lecture = nagruzki[i].Hour.ToString();
                if (nagruzki[i].SubjectItem.LessonType == LessonTypes.Практика)
                    item.Practika = nagruzki[i].Hour.ToString();
                Jurnaly.Instance.Add(item);
            }
            AccessDb.Instance.Commit();

            reportViewer1.LocalReport.DataSources.Clear();

            foreach (ReportDataSource source in GetReportDataSources())
            {
                reportViewer1.LocalReport.DataSources.Add(source);
            }

            this.reportViewer1.RefreshReport();
        }
    }
}